import requests
from requests import Session
import time
import re
from concurrent.futures import ThreadPoolExecutor, as_completed
from localORC import getOCRtext, compress_string
from PIL import Image
import cv2
import numpy as np
from mySerial import getCOMport, sendCom
# 1 1#主机非电气量
# 2 2#主机非电气量
# 3 3#主机非电气量
# 4 4#主机非电气量
# 5 电气量
# 6 电气设备记录
# 7 变频机组电气量
# 8 空
# 9 空
# 10 扬压力
# 月报
# http://192.168.100.10:8081/LLJBBXT/averageyueServlet
# 参数：nianyue: 2024-03
# http://192.168.100.10:8081/LLJBBXT/averagenianServlet
# 参数：nian: 2024
# http://192.168.100.10:8081/LLJBBXT/LLJHISServlet
# 参数：
# startTime: 2024-03-22 00:00:00
# endTime: 2024-03-22 23:59:59
# STCD: 1
# 0:00	20.6	25.2	21.3	21.1	21.2	19.7	21.2	19.6	0.2	0.8	1.0	1.0	7.0	8.0	1.0	1.0	1.0	0.0	0.0	0.0	18.3	0.0	18.65	16.02	16.07	2.58	0.00	0.00	-3.9	0.0	0.00
'''
code:
get
http://192.168.100.10:8081/LLJBZ/system/verifyCode/create?random=0.028668926513046644


post:
http://192.168.100.10:8081/LLJBZ/system/user/system_login
KEYDATA=admin%2Ctalent%2Cadmin%2Ctalent%2C4036


Set-Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoi566h55CG5ZGYIiwidXNlcklkIjoiNmZmZDFiMTktNThlOS00NzVkLTk5ZTUtYWMxMWFkZWFkZTU1Iiwic3ViIjoiYWRtaW4iLCJpc3MiOiIwOThmNmJjZDQ2MjFkMzczY2FkZTRlODMyNjI3YjRmNiIsImlhdCI6MTcxNjg3ODAwNSwiYXVkIjoicmVzdGFwaXVzZXIiLCJleHAiOjE3MTY4OTI0MDUsIm5iZiI6MTcxNjg3ODAwNX0.Q9ucGeSH0wRMhh3TTGAfiLwhfQAFLfwQj7K-Ep1QtbY; 
Max-Age=14400; Expires=Tue, 28-May-2024 10:33:25 GMT; Path=/LLJBZ

'''
TIME_FLAG = 300
TIME_NET = 3720


def login():
    kernel = np.ones((2, 2), np.uint8)
    session = Session()
    result = []
    while 1:
        resp = session.get(
            url=
            'http://192.168.100.10:8081/LLJBZ/system/verifyCode/create?random=0.028668926513046644'
        )

        # with open('./code.png', 'wb') as f:
        #     f.write(resp.content)
        img_buffer_numpy = np.frombuffer(resp.content, dtype=np.uint8)
        img_numpy = cv2.imdecode(img_buffer_numpy, 1)
        img_numpy = cv2.resize(img_numpy, (0, 0),
                               fx=2,
                               fy=2,
                               interpolation=cv2.INTER_CUBIC)
        # cv2.imwrite('./img_numpy.png',img_numpy)
        img_gray = cv2.cvtColor(img_numpy, cv2.COLOR_BGR2GRAY)
        # cv2.imwrite('./img_gray.png',img_gray)
        # byteStream = io.BytesIO(resp.content)
        # image = Image.open(byteStream)
        # resize_image = image.resize(
        #     ((500, int(image.size[1] * 500 / image.size[0]))))
        # resize_image = resize_image.convert('L')
        # resize_image.save('./code_resize.png')
        # img = cv2.cvtColor(np.asarray(resize_image), cv2.COLOR_RGB2BGR)
        ret, img = cv2.threshold(img_gray, 127, 255, cv2.THRESH_BINARY)
        # cv2.imwrite('./img_threshold.png',img)
        dilate_image = cv2.dilate(img, kernel, iterations=1)
        # cv2.imwrite('./code_dilate.png', dilate_image)
        erode_image = cv2.erode(dilate_image, kernel, iterations=1)
        # cv2.imwrite('./code_erode.png', erode_image)
        # result_image = Image.fromarray(dilate_image)
        result_image = Image.fromarray(erode_image)
        # result_image.save('./code1.png')
        code = getOCRtext(result_image)
        if code:
            if code[0]:
                code = code[0][0][1][0]
                # print(code)
                code1 = re.findall(r'\d+', code)
                print(code1)
                if code1:
                    code1 = ''.join(code1)
                    if len(code1) == 4:
                        break
    # print(code1)
    # http://192.168.100.10:8081/LLJBZ/system/user/system_login
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'X-Requested-With': 'XMLHttpRequest',
        'User-Agent':
        'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    }
    session.cookies.update({
        'Hm_lvt_82116c626a8d504a5c0675073362ef6f':
        '1711592231,1712735867,1713320325'
    })
    resp = session.post(
        url='http://192.168.100.10:8081/LLJBZ/system/user/system_login',
        headers=headers,
        data=f'KEYDATA=admin%2Ctalent%2Cadmin%2Ctalent%2C{code1}')
    if resp.json()['result'] == 'success':
        result_list = get_serverdata(ss=session)
        result_list.sort()
        array_head = ['6']
        data_list = []
        count = 0
        for item in result_list:
            temp_head = re.findall(r'(.*?)[-|_].*?', item[0])
            if temp_head != array_head:
                if data_list:
                    count += 1
                    # print(count, '头', array_head)
                    # print('发送数据')
                    # print(compress_string(str(array_head + data_list)))
                    result.append((str(array_head + data_list)))
                    data_list = []
                array_head = temp_head
            data_list.append(item[1])
        # print(count, '头', array_head)
        result.append((str(array_head + data_list)))
        # print('发送数据')
        return result


def get_data(STCD):
    '''
    获取数据库数据
    STCD: 10为测压管
    返回json
    '''
    data = {
        "startTime": f"{time.strftime('%Y-%m-%d %H:00:00',time.localtime())}",
        "endTime": f"{time.strftime('%Y-%m-%d %H:59:59',time.localtime())}",
        "STCD": STCD
    }
    try:
        resp = requests.post(
            "http://192.168.100.10:8081/LLJBBXT/LLJHISServlet", data=data)
        # print(resp.json())
        return resp.json()
    except Exception as e:
        return str(e)


# 请求处理函数
def fetch_url(url, ss):
    response = ss.get(
        url=url,
        # headers={
        #     "Cookie":
        #     "JSESSIONID=BA15CD9044A560F50AC74922C854190B; token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoi566h55CG5ZGYIiwidXNlcklkIjoiYzk3YTcxZjktMzQ3Zi00MmFmLTg0ZjktYmNlODhiMTg0NzQ3Iiwic3ViIjoiYWRtaW4iLCJpc3MiOiIwOThmNmJjZDQ2MjFkMzczY2FkZTRlODMyNjI3YjRmNiIsImlhdCI6MTcxNjg2NDMwNCwiYXVkIjoicmVzdGFwaXVzZXIiLCJleHAiOjE3MTY4Nzg3MDQsIm5iZiI6MTcxNjg2NDMwNH0.4wykrIT-H_vdrQf5UXEk1gdbfjc4hUHL8x36nMWERnc; userName=admin; authLevel=0; Hm_lvt_82116c626a8d504a5c0675073362ef6f=1711592231,1712735867,17133203"
        # }
    )
    # print(response.text)
    # 这里可以根据需要处理response，例如检查状态码、解析响应内容等
    return url, response.status_code, response.json()


def get_serverdata(ss):
    '''
    服务器取值
    '''
    urls = [
        "http://192.168.100.10:8081/LLJBZ/work/realData/Alarm_Set/findAll",
        "http://192.168.100.10:8081/LLJBZ/work/bzRealData/bzYxReal/findAll",
        "http://192.168.100.10:8081/LLJBZ/work/bzRealData/bzYcReal/findAll",
    ]

    # 使用线程池执行请求
    with ThreadPoolExecutor(
            max_workers=len(urls)) as executor:  # max_workers根据实际情况调整
        futures = {executor.submit(fetch_url, url, ss) for url in urls}
        # 收集结果
        results = []
        for future in as_completed(futures):
            try:
                url, status_code, content = future.result()
                print(
                    f"URL: {url}, Status Code: {status_code}, Content Length: {len(content)}"
                )
                if status_code == 200:
                    results += json_to_uart(content)
            except Exception as e:
                print(f"Error fetching {future}: {e}")
    # 所有请求完成后，results列表中包含了每个URL请求的返回信息
    print("所有请求完成，结果收集完毕。")
    # results.sort()
    return results


def json_to_uart(resp_json):
    '''
    处理数据
    '''
    samplevalue = 'sampleValue'
    if type(resp_json) != list:
        resp_json = resp_json['data']
        samplevalue = 'samplevalue'
    # result_dict = {}
    result_list = []
    for r in resp_json:
        result_list.append((f"{r['zdy']}", f"{r[samplevalue]}"))
        # 循环里 直接串口发送
    return result_list


def tosendcontent(resp_text):
    '''
    转换成发送内容
    '''
    result = []
    for r in resp_text:
        result.append(f"{r['tagID']}={r['value']}")
    result = f"({'&'.join(result)})"
    # print(result)
    return result


def loop():
    while 1:
        com_port = getCOMport('USB-Enhanced-SERIAL CH343')  #正式用
        #print(com_port)
        # com_port = "COM11"  #测试用
        while com_port:
            if (int(time.time()) - 6) % TIME_NET == 0:
                print('发送数据库数据')
                cyg_data = get_data(10)
                sendContent = login()
                # sendContent = tosendcontent(cyg_data)
                sendCom(com_port[0], 115200, sendContent)
                time.sleep(1)


if __name__ == "__main__":
    print(login())
